package com.ai.deepseekspring.service.impl;


import com.ai.deepseekspring.service.BaiLianDpService;

import com.ai.deepseekspring.service.VectorService;
import com.ai.deepseekspring.utils.RequestUtil;
import com.ai.deepseekspring.utils.TokenUtil;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BaiLianDpServiceImpl implements BaiLianDpService {


    @Autowired
    private VectorService vectorService;

    @Autowired
    private ChatMemory chatMemory; //注入的是 ChatStorageMemory

    @Override
    public String chat(String msg,ChatClient client) {
        String userid = TokenUtil.parseToken( //解析token
                        RequestUtil.getTokenFromHeader() //获取token
                )
                .get("id")
                .toString();

        String safeMsg = StringUtils.hasText(msg) ? msg : "";
        System.out.println(safeMsg);


        try {
            // 检索并仅提取文档 content，减少噪声
            if (StringUtils.hasText(safeMsg)) {

                List<Document> docs = vectorService.find(safeMsg);
                System.out.println(docs);
                if (docs != null && !docs.isEmpty()) {
                    System.out.println("检索到相关内容，条数：" + docs.size());
                    // 取前 3 条 content 合并为事实
                    String facts = (String) docs.stream()
                            .limit(3)
                            .map(doc -> doc.getText())
                            .collect(Collectors.joining(";"));

                    if (StringUtils.hasText(facts)) {
                        safeMsg = "已知事实：" + facts + "。基于以上，请回答问题：" + safeMsg;
                    }

                }

            }
        } catch (Exception e) {
            System.out.println("检索相关内容出错，忽略错误继续对话，err=" + e.toString());
        }


        String response = client.prompt()
                .user(safeMsg)
                .advisors(
                        MessageChatMemoryAdvisor //这里就将聊天记忆顾问加入到对话中 把写好的chatMemory甩给他就完事了
                        .builder(chatMemory)
                        .conversationId(userid)
                                .order(0)
                        .build())

                .call()
                .content();
        return response;
    }


}
